package com.borun.controller.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.borun.entity.QuizBean;
import com.borun.entity.WordBean;
import com.borun.service.WordService;
import com.borun.util.RandomUtils;
import com.borun.util.RespUtils;

@Controller
@ResponseBody
@RequestMapping("/api")
public class HomeApiController {

	@Autowired
	private WordService wordService;
	
	private List<WordBean> wordsList = new ArrayList<WordBean>();
	
	@RequestMapping(value="/quiz",method=RequestMethod.POST)
	public JSONObject getQuizs(Integer base_id){
		
		List<WordBean> wordBeans = wordService.findByWordBase(base_id);	

//		if(wordBeans.size() < 10){
//			return RespUtils.createQuizResp("当前词库单词不足10个，请添加单词或选择其他词库！");
//		}		
		// 最终答题
		List<QuizBean> Quizs = new ArrayList<QuizBean>();
		// 每组答题的单词
		List<WordBean> quizWords = new ArrayList<WordBean>();
	
		try {
			Collections.shuffle(wordBeans); 
			if(wordBeans.size() > 10)
				quizWords = wordBeans.subList(0, 10);
			else 
				quizWords = wordBeans;
			
			System.out.println("quizWords:"+quizWords.size());	
			
			for(WordBean model:quizWords){
				Quizs.add(transform(model, base_id));
			}	
		} catch (Exception e) {
			return RespUtils.createQuizResp("出题失败！请检查当前词库是否为空或适当添加单词");
		}

        return RespUtils.createQuizResp("出题成功！",Quizs);
	}
	
	
	private QuizBean transform(WordBean wordBean,Integer base_id){	
		
		wordsList = wordService.findByWordBase(base_id);
		
		// 得到当前单词的索引
		int index = wordsList.indexOf(wordBean);
		// 删除当前单词
		wordsList.remove(index);
		// 打乱剩下的单词次序
		Collections.shuffle(wordsList); 	
		// 创建其他选项
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 3; i++) {
			list.add(wordsList.get(i).getEnglish());
		}	
		// 生成正确答案的位置
		int correctIndex = RandomUtils.generate(0, 3);
		//System.out.println("correctIndex:"+correctIndex);
		// 将正确答案随机插入选项
		list.add(correctIndex, wordBean.getEnglish());	
		//return null;
		String[] strings = new String[list.size()];
		
		return new QuizBean(wordBean.getChinese(),list.toArray(strings),correctIndex+1);
	}
	
	
	
	
}
